//
//  HACPainterDisplay.m
//  HStockCharts
//
//  Created by Hotacool on 2018/9/17.
//

#import "HACPainterDisplay.h"

#import "_ASAsyncTransactionGroup.h"
#import "_ASAsyncTransactionContainer.h"
#import "_ASAsyncTransaction.h"

@interface HACPainterDisplay ()
@property (nonatomic, copy) CompletionBlock completionBlock ;
@end

@implementation HACPainterDisplay

+ (dispatch_queue_t)displayQueue {
    static dispatch_queue_t displayQueue = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        displayQueue = dispatch_queue_create("HACPainter.displayQueue", DISPATCH_QUEUE_CONCURRENT);
        // we use the highpri queue to prioritize UI rendering over other async operations
        dispatch_set_target_queue(displayQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    });
    return displayQueue;
}

+ (dispatch_queue_t)serialOperationQueue {
    static dispatch_queue_t serialOperationQueue = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        serialOperationQueue = dispatch_queue_create("HACPainter.serialOperationQueue", DISPATCH_QUEUE_SERIAL);
        // we use the highpri queue to prioritize UI rendering over other async operations
        dispatch_set_target_queue(serialOperationQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    });
    return serialOperationQueue;
}

- (void)addCompletionBlock:(CompletionBlock)block {
    self.completionBlock = block;
}

- (void)displayLayer:(CALayer<HACAsynchronousAble> *)layer asynchronously:(BOOL)asynchronously {
    if (layer.displaysAsynchronously) {
        asyncdisplaykit_async_transaction_operation_block_t displayBlock = ^id{
            dispatch_async(dispatch_get_main_queue(), ^{
                [layer supperDisplay];
            });
            return nil;
        };
        asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id<NSObject> value, BOOL canceled){
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.completionBlock) {
                    self.completionBlock(value, canceled);
                }
            });
        };
        dispatch_async(dispatch_get_main_queue(), ^{
            _ASAsyncTransaction *transaction = layer.asyncdisplaykit_asyncTransaction;
            [transaction addOperationWithBlock:displayBlock priority:100 queue:[HACPainterDisplay displayQueue] completion:completionBlock];
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [layer supperDisplay];
        });
    }
}

@end
